package com.tiamosu.navigation.demo.ui.fragments

import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.tiamosu.databinding.delegate.lazyDataBindingOrNull
import com.tiamosu.databinding.page.DataBindingConfig
import com.tiamosu.navigation.demo.R
import com.tiamosu.navigation.demo.base.BaseFragment
import com.tiamosu.navigation.demo.databinding.FragmentMainBinding
import com.tiamosu.navigation.demo.ext.init
import com.tiamosu.navigation.demo.sharedViewModel
import com.tiamosu.navigation.ext.lifecycleOwnerEx

/**
 * @author tiamosu
 * @date 2021/5/7.
 */
class MainFragment : BaseFragment() {
    private val dataBinding: FragmentMainBinding? by lazyDataBindingOrNull()

    private val fragments by lazy {
        arrayListOf<Class<out Fragment>>().apply {
            add(AFragment::class.java)
            add(BFragment::class.java)
            add(CFragment::class.java)
        }
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.fragment_main)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e("susu", "test1:${dataBinding?.mainTabBarLayout}")
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.e("susu", "test2:${dataBinding?.mainTabBarLayout}")
    }

    override fun doBusiness() {
        dataBinding?.mainVp2?.init(this, fragments)
        dataBinding?.mainVp2?.let {
            dataBinding?.mainTabBarLayout?.setViewPager2(it)
        }

        sharedViewModel.selectTabItem.observe(lifecycleOwnerEx) { cls ->
            val index = fragments.indexOf(cls)
            dataBinding?.mainVp2?.setCurrentItem(index, false)
        }

        dataBinding?.mainTabBarLayout?.setOnItemSelectedListener(
            onItemSelected = { position, prePosition ->
                Log.e("susu", "onItemSelected --- position:$position   prePosition:$prePosition")
            },
            onItemUnselected = { position ->
                Log.e("susu", "onItemUnselected --- position:$position")
            },
            onItemReselected = { position ->
                Log.e("susu", "onItemReselected --- position:$position")
            }
        )
    }

    /**
     * Fragment回退拦截处理
     */
    override fun onBackPressedSupport(): Boolean {
        if (System.currentTimeMillis() - TOUCH_TIME < WAIT_TIME) {
            activity.finish()
        } else {
            TOUCH_TIME = System.currentTimeMillis()
            Toast.makeText(context, "再按一次退出", Toast.LENGTH_LONG).show()
        }
        return true
    }

    companion object {
        // 再点一次退出程序时间设置
        private const val WAIT_TIME = 2000L
        private var TOUCH_TIME: Long = 0
    }
}